﻿
#region Imports...
using System;
using System.Web.UI.WebControls;
using Pharmacy.Web.UI;
using Pharmacy.Settings.BusinessLayer;
using Pharmacy.Data;
using Pharmacy.Entities;
using System.Web.Services;
#endregion

public partial class GrnEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtil.RedirectAfterInsertUpdate(FormView1, "GrnImports.aspx?{0}", GrnDataSource);
        FormUtil.RedirectAfterCancel(FormView1, "Grn.aspx");
        FormUtil.SetDefaultMode(FormView1, "GrnId");
        if (!IsPostBack)
        {
            GetWhereClause();
            SellPriceNew.Attributes.Add("readonly", "readonly");
        }
    }

    protected void GetWhereClause()
    {
        //try
        //{


        DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
        string PoID = ddPoID.SelectedValue;

        int count = 0;
        string WhereClause = "POID= '" + PoID + "' and RemainQuantity >0";
        TList<PoDetails> listPodetail = DataRepository.PoDetailsProvider.GetPaged(WhereClause, "", 0, 1000, out count);
        DataRepository.PoDetailsProvider.DeepLoad(listPodetail);
        TList<DrugDispo> objList = new TList<DrugDispo>();
        foreach (PoDetails detail in listPodetail)
            objList.Add(detail.DrugIdSource);
        dataDrugId.Items.Clear();
        dataDrugId.DataSource = objList;
        dataDrugId.DataTextField = "DrugName";
        dataDrugId.DataValueField = "DrugId";
        dataDrugId.DataBind();
        //}
        //catch (Exception)
        //{

        //}
    }

    protected void GridViewGrnDetails1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string urlParams = string.Format("GrnDetailId={0}", GridViewGrnDetails1.SelectedDataKey.Values[0]);
        Response.Redirect("GrnDetailsEdit.aspx?" + urlParams, true);
    }
    protected void FormView1_Load(object sender, EventArgs e)
    {
        DropDownList dataPreparedBy = (DropDownList)FormView1.Row.FindControl("dataPreparedBy");
        dataPreparedBy.Enabled = false;
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            TextBox tbGrnID = (TextBox)FormView1.Row.FindControl("dataGrnID");
            TextBox tbGrnDate = (TextBox)FormView1.Row.FindControl("dataGrnDate");

            //ServiceFacade.SettingsHelper.GRNPrefix = "RN-01-";
            string Perfix = "G" + ServiceFacade.SettingsHelper.GRNPrefix + DateTime.Now.ToString("yyMMdd");
            int Count = 0;
            TList<Grn> objGRN = DataRepository.GrnProvider.GetPaged("GrnId like '" + Perfix + "' + '%'", "GrnId desc", 0, 1, out Count);
            if (Count == 0)
                tbGrnID.Text = Perfix + "-" + "001";
            else
            {
                tbGrnID.Text = Perfix + "-" + String.Format("{0:000}", int.Parse(objGRN[0].GrnId.Substring((objGRN[0].GrnId.Length - 3))) + 1);
            }
            tbGrnDate.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            tbGrnDate.Enabled = false;
            dataPreparedBy.SelectedValue = Request.Cookies["LoginUser"].Value;
        }
        else
        {
            FormView1.FooterRow.FindControl("PreviewButton").Visible = true;
            string grnId = Request.QueryString["GrnId"];
            Grn objGrn = DataRepository.GrnProvider.GetByGrnId(grnId);
            if (objGrn.IsComplete)
            {
                FormView1.FooterRow.FindControl("UpdateButton").Visible = false;
                FormView1.FooterRow.FindControl("CloseGrn").Visible = false;
            }
            else
            {
                FormView1.FooterRow.FindControl("CloseGrn").Visible = true;
                pn_GrnDetailsAdd.Visible = true;
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (btnSave.Text == "Add")
        {
            TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
            DateTime? expDate; DateTime dt;
            expDate = DateTime.TryParse(txtExpDate.Value, out dt) ? dt : (DateTime?)null;
            GrnDetails objDetails = new GrnDetails();
            string batchLot = null;
            batchLot = (string.IsNullOrEmpty(TxtBatchLot.Value) == true) ? null : TxtBatchLot.Value;

            try
            {
                objTransactionManager.BeginTransaction();
                objDetails.DrugId = dataDrugId.SelectedValue;
                objDetails.Quantity = Int32.Parse(tbQuantity.Value);
                objDetails.Remark = tbRemark.Value;
                objDetails.BatchLot = batchLot;
                objDetails.ExpDate = expDate;
                objDetails.UnitPrice = decimal.Parse(CostPriceResult.Value);
                TextBox dataGRN = (TextBox)FormView1.Row.FindControl("dataGrnId");
                objDetails.GrnId = dataGRN.Text;
                DataRepository.GrnDetailsProvider.Insert(objTransactionManager, objDetails);



                // update costprice and sellprice DrugDispo
                DrugDispo objDrugDispo = DataRepository.DrugDispoProvider.GetByDrugId(objTransactionManager, objDetails.DrugId);
                if (objDrugDispo != null)
                {
                    if (objDrugDispo.CostPrice != decimal.Parse(CostPriceResult.Value))
                        objDrugDispo.CostPrice = decimal.Parse(CostPriceResult.Value);
                    if (objDrugDispo.SellPrice != decimal.Parse(SellPriceNew.Value))
                        objDrugDispo.SellPrice = decimal.Parse(SellPriceNew.Value);
                    DataRepository.DrugDispoProvider.Update(objTransactionManager, objDrugDispo);
                }

                //update Podetail
                int countlistpo = 0;
                DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
                TList<PoDetails> listPodetail = DataRepository.PoDetailsProvider.GetPaged(objTransactionManager, "PoId='" + ddPoID.SelectedValue + "' and DrugId='" + dataDrugId.SelectedValue + "'", "", 0, 1, out countlistpo);
                if (countlistpo == 1)
                {
                    listPodetail[0].RemainQuantity -= Int32.Parse(tbQuantity.Value);
                    DataRepository.PoDetailsProvider.Update(objTransactionManager, listPodetail[0]);

                }
                objTransactionManager.Commit();
                GridViewGrnDetails1.DataBind();
                GetWhereClause();
                tbRemark.Value = "";
                tbQuantity.Value = "";
                dataDrugId.SelectedValue = "";
                dataDrugId.Focus();

            }
            catch (Exception exception)
            {
                objTransactionManager.Rollback();
                throw exception;
            }
        }
    }

    public void DeleteGrnDetail(string GrnDetailId, string PoId)
    {
        int count = 0;
        int countstock = 0;
        decimal Amount = 0;

        GrnDetails objGrnDetail = DataRepository.GrnDetailsProvider.GetByGrnDetailId(long.Parse(GrnDetailId));
        TList<PoDetails> listPoDetail = DataRepository.PoDetailsProvider.GetPaged("PoId='" + PoId + "' and DrugId ='" + objGrnDetail.DrugId + "'", "", 0, 1000, out  count);
        //set poquantity
        listPoDetail[0].RemainQuantity += objGrnDetail.Quantity;
        Amount = objGrnDetail.UnitPrice * objGrnDetail.Quantity;
        Grn objGrn = DataRepository.GrnProvider.GetByGrnId(objGrnDetail.GrnId);
        TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
        //update Podetails
        try
        {
            objTransactionManager.BeginTransaction();
            DataRepository.PoDetailsProvider.Update(objTransactionManager, listPoDetail[0]);
            DataRepository.GrnDetailsProvider.Delete(objTransactionManager, long.Parse(GrnDetailId));
            //update Amount Grn
            objGrn.Amount -= Amount;
            objGrn.TotalAmount = objGrn.Amount + objGrn.Vat;
            DataRepository.GrnProvider.Update(objTransactionManager, objGrn);
            objTransactionManager.Commit();

        }
        catch (Exception)
        {
            objTransactionManager.Rollback();

        }
        finally
        {

            GetWhereClause();
        }


    }

    protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "CloseGrn")
        {
            decimal Amount = 0;
            decimal totalAmount = 0;
            TextBox tbGrnID = (TextBox)FormView1.Row.FindControl("dataGrnID");

            //check Po and close Po
            int countPo = 0;
            TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
            try
            {
                objTransactionManager.BeginTransaction();
                DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
                TList<PoDetails> listPoDetail = DataRepository.PoDetailsProvider.GetPaged("PoId='" + ddPoID.SelectedValue + "' And RemainQuantity >0", "", 0, 1000, out countPo);
                if (countPo == 0) //kiem tra khong ton tai po nao co remainquantity>0
                {
                    Po objPo = DataRepository.PoProvider.GetByPoId(ddPoID.SelectedValue);
                    objPo.IsComplete = true;
                    DataRepository.PoProvider.Update(objTransactionManager, objPo);
                }

                //update stock
                Stock objStock;
                TList<GrnDetails> listGrnDetail = DataRepository.GrnDetailsProvider.GetByGrnId(tbGrnID.Text);
                foreach (GrnDetails Itemdetail in listGrnDetail)
                {
                    objStock = DataRepository.StockProvider.GetByDrugIdExpDateBatchLot(objTransactionManager, Itemdetail.DrugId, Itemdetail.ExpDate, Itemdetail.BatchLot);
                    if (objStock != null)
                    {
                        objStock.Quantity += Itemdetail.Quantity;
                        objStock.UnitPrice = Itemdetail.UnitPrice;
                        DataRepository.StockProvider.Update(objTransactionManager, objStock);
                    }
                    else
                    {
                        objStock = new Stock();
                        objStock.DrugId = Itemdetail.DrugId;
                        objStock.Quantity = Itemdetail.Quantity;
                        objStock.UnitPrice = Itemdetail.UnitPrice;
                        objStock.ExpDate = Itemdetail.ExpDate;
                        objStock.BatchLot = Itemdetail.BatchLot;
                        DataRepository.StockProvider.Insert(objTransactionManager, objStock);
                    }
                    // tinh amount cho Grn_Amount
                    Amount = Itemdetail.Quantity * Itemdetail.UnitPrice;
                    totalAmount += Amount;
                }
                //update Amount Grn
                Grn objGrn = DataRepository.GrnProvider.GetByGrnId(tbGrnID.Text);
                if (objGrn != null)
                {
                    objGrn.IsComplete = true;
                    objGrn.Amount = totalAmount;
                    DataRepository.GrnProvider.Update(objTransactionManager, objGrn);
                }
                objTransactionManager.Commit();
            }
            catch (Exception exception)
            {
                objTransactionManager.Rollback();
                throw exception;
            }
            finally
            {
                //visible button
                FormView1.FooterRow.FindControl("CloseGrn").Visible = false;
            }
        }
        if (e.CommandName == "Preview")
        {
            string grnId = Request.QueryString["GrnId"].ToString();
            Response.Redirect("PreviewGrn.aspx?GrnId=" + grnId);
        }
    }

    protected void FormView1_ItemCreated(object sender, EventArgs e)
    {
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            int count = 0;
            //DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
            //TList<Po> listPo = DataRepository.PoProvider.GetPaged("IsComplete=0","", 0, Int32.MaxValue, out count);
            //ddPoID.DataSource = listPo;
            //ddPoID.DataTextField = "PoId";
            //ddPoID.DataValueField = "PoId";
            //ddPoID.DataBind();
            //ddPoID.Items.Add("< Please Choose ...>");
            //ddPoID.SelectedValue = "< Please Choose ...>";
        }
        else
        {
            Grn grn = DataRepository.GrnProvider.GetByGrnId(Request.QueryString["GrnId"]);
            DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
            //HiddenField hdPoID = (HiddenField)FormView1.Row.FindControl("HdPoId");
            //Po objpo=new Po();
            //objpo.PoId= hdPoID.Value;
            ddPoID.Items.Add(grn.PoId);
            //ddPoID.SelectedValue = "Test";
            ddPoID.Enabled = false;

        }
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        LinkButton btn_Delete = (LinkButton)sender;
        GridViewRow deleteRow = (GridViewRow)btn_Delete.NamingContainer;
        DropDownList ddPoID = (DropDownList)FormView1.Row.FindControl("dataPoID");
        string grnDetailId = GridViewGrnDetails1.DataKeys[deleteRow.RowIndex].Value.ToString();
        DeleteGrnDetail(grnDetailId, ddPoID.SelectedValue);
        GridViewGrnDetails1.DataBind();
    }
}


